#include <iostream>
#include <string>
#include <functional>
#include <vector>
#include <unistd.h>
#include <pthread.h>
#include <time.h>

using func_t = std::function<void()>;

class ThreadData
{
public:
    ThreadData(const std::string& name, const uint64_t& time, func_t f)
    : threadName(name)
    , createTime(time)
    , func(f)
    {}
public:
    std::string threadName;
    uint64_t createTime;
    func_t func;
};

std::string toHex(pthread_t tid)
{
    char id[64];
    snprintf(id, sizeof(id)-1, "0x%x", tid);
    return id;
}

void* threadRoutine1(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args); //安全强转
    std::cout << "thread name: " << td->threadName 
        << " create time: " << td->createTime 
        << " thread id: " << toHex(pthread_self()) 
        << std::endl;
    td->func();
    sleep(2);
    delete td;
    
    //线程终止
    return nullptr;
    // pthread_exit(nullptr);
}

int main1()
{
    std::vector<pthread_t> pthreads;
    for(int i = 0; i < 5; i++) 
    {
        char threadName[64];
        snprintf(threadName, sizeof(threadName)-1, "%s-%d", "thread", i);

        pthread_t tid;
        ThreadData* td = new ThreadData(threadName, (uint64_t)time(nullptr), [threadName](){
            std::cout << "part of " << threadName << std::endl;
        });
        pthread_create(&tid, nullptr, threadRoutine1, td); //可以传任意类型，和对象
        pthreads.push_back(tid);
        sleep(1);
    }

    std::cout << "*** tid: ";
    for(const auto& tid : pthreads) 
    {
        std::cout << tid << " ";
    }
    std::cout << "***" << std::endl;

    while(true)
    {
        std::cout << "***main thread***" << std::endl;
        sleep(1);
    }

    return 0;
}





void* threadRoutine2(void* args)
{
    // pthread_detach(pthread_self()); //线程分离，由新线程提出
    std::cout << (const char*)args << " running..." << std::endl;
    sleep(2);
    
    //线程终止
    return (void*)"thread done...";
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, threadRoutine2, (void*)"thread-0");
    std::cout << "main thread id: " << toHex(pthread_self()) << std::endl;
    // pthread_detach(tid); //线程分离，由主线程提出
    // pthread_cancel(tid); //线程取消

    void* ret = nullptr;
    int n = pthread_join(tid, &ret); //等待tid执行流汇入主线程
    std::cout << (const char*)ret << ", n:" << n << std::endl;

    return 0;
}